package org.example.service;

import lombok.RequiredArgsConstructor;
import org.example.dto.CourseDto;
import org.example.dto.CourseRequestDto;
import org.example.dto.PageDto;
import org.example.dto.ResultDto;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

@Service
@RequiredArgsConstructor
public class CourseService {
    private final RestTemplate restTemplate;

    //POST方式，通过body传递JSON
    public ResultDto<PageDto<CourseDto>> findCourseByJson(CourseRequestDto course){
        ParameterizedTypeReference<ResultDto<PageDto<CourseDto>>> pt = new ParameterizedTypeReference<>() {};
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<CourseRequestDto> entity = new HttpEntity<>(course, headers);
        ResponseEntity<ResultDto<PageDto<CourseDto>>> result =
                restTemplate.exchange("http://producer-demo/courses", HttpMethod.POST, entity, pt);
        return result.getBody();
    }

   // GET方式，通过路径传递参数
    public ResultDto<PageDto<CourseDto>> findCourseByPath(String account, Integer page, Integer rows){
        ParameterizedTypeReference<ResultDto<PageDto<CourseDto>>> pt = new ParameterizedTypeReference<>() {};
        ResponseEntity<ResultDto<PageDto<CourseDto>>> result =
                restTemplate.exchange("http://producer-demo/courses/{account}/{page}/{rows}", HttpMethod.GET,
                        HttpEntity.EMPTY,pt,
                        account, page, rows);
        return result.getBody();
    }
   //POST方式，通过表单传递参数
    public ResultDto<PageDto<CourseDto>> findCourseByForm(CourseRequestDto course){
        ParameterizedTypeReference<ResultDto<PageDto<CourseDto>>> pt = new ParameterizedTypeReference<>() {};
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String,Object> params = new LinkedMultiValueMap<>();
        params.add("account", course.getAccount());
        params.add("page", course.getPage());
        params.add("rows", course.getRows());
        HttpEntity<CourseRequestDto> entity = new HttpEntity(params, headers);
        ResponseEntity<ResultDto<PageDto<CourseDto>>> result =
                restTemplate.exchange("http://producer-demo/courses1", HttpMethod.POST, entity, pt);
        return result.getBody();
    }
}
